﻿using System;
using fastCSharp;
using fastCSharp.code.cSharp;

namespace diantou.web
{
    /// <summary>
    /// 公共调用
    /// </summary>
    class pub
    {
        /// <summary>
        /// 用户Cookie名称
        /// </summary>
        private static readonly byte[] userCookieName = ("User").getBytes();
        /// <summary>
        /// 模拟用户标识Cookie名称
        /// </summary>
        private static readonly byte[] simulationUserIdCookieName = ("SimulationUserId").getBytes();
        /// <summary>
        /// 考试用户Cookie名称
        /// </summary>
        private static readonly byte[] examUserCookieName = ("ExamUser").getBytes();
        /// <summary>
        /// 程序员用户登录Cookie名称
        /// </summary>
        internal static readonly byte[] IndexLoginCookieName = ("IndexLogin").getBytes();
        /// <summary>
        /// 获取当前用户
        /// </summary>
        /// <param name="page">Web页面</param>
        /// <param name="sessionId">session用户标识</param>
        /// <param name="error">错误信息</param>
        /// <returns>当前用户</returns>
        private static diantou.dataAccess.user getCurrentUser(webPage.page page, out int sessionId)
        {
            webConfig.session session = page.GetSession<webConfig.session>(default(webConfig.session));
            if (session.Type == webConfig.session.type.User)
            {
                if ((sessionId = session.Id) == 0)
                {
                    string cookie = page.GetCookie(userCookieName);
                    if (cookie != null)
                    {
                        int userId;
                        subArray<subString> cookies = cookie.split('.');
                        if (cookies.Count >= 3 && int.TryParse(cookies[0], out userId))
                        {
                            diantou.dataAccess.user user = diantou.dataAccess.clientCache.User[userId];
                            if (user != null && !user.IsLock && user.Password.Length != 0 && (user.RegisterVerify == 0 || user.WebsiteName.Length != 0))
                            {
                                if (cookies[2].Equals(diantou.dataAccess.user.Md5Password(cookies[1] + user.Password)))
                                {
                                    page.SetSession<webConfig.session>(new webConfig.session { Id = userId });
                                    return user;
                                }
                            }
                        }
                    }
                }
                else if (sessionId > 0) return diantou.dataAccess.clientCache.User[sessionId];
            }
            sessionId = 0;
            return null;
        }
        /// <summary>
        /// 获取当前用户
        /// </summary>
        /// <param name="page">Web页面</param>
        /// <returns>当前用户</returns>
        internal static diantou.dataAccess.user GetCurrentUser(webPage.page page)
        {
            int sessionId;
            diantou.dataAccess.user user = getCurrentUser(page, out sessionId);
            if (user != null)
            {
                if (user.IsLock)
                {
                    if (sessionId >= 0) page.RemoveSession();
                    removeUserCookie(page);
                }
                else return getSimulationUser(page, user);
            }
            return null;
        }
        /// <summary>
        /// 获取当前用户
        /// </summary>
        /// <param name="page"></param>
        /// <returns></returns>
        internal static diantou.dataAccess.user GetSessionUser(webPage.page page)
        {
            webConfig.session session = page.GetSession<webConfig.session>(default(webConfig.session));
            if (session.Id > 0 && session.Type == webConfig.session.type.User)
            {
                diantou.dataAccess.user user = diantou.dataAccess.clientCache.User[session.Id];
                if (!user.IsLock) return getSimulationUser(page, user);
            }
            return null;
        }
        /// <summary>
        /// 获取模拟用户
        /// </summary>
        /// <param name="page"></param>
        /// <param name="user"></param>
        /// <returns></returns>
        private static diantou.dataAccess.user getSimulationUser(webPage.page page, diantou.dataAccess.user user)
        {
            user.SimulationUserId = 0;
            if (user.Permission == dataModel.user.permission.Admin)
            {
                string simulationUserId = page.GetCookie(simulationUserIdCookieName);
                int userId;
                if (int.TryParse(simulationUserId, out userId))
                {
                    diantou.dataAccess.user simulationUser = diantou.dataAccess.clientCache.User[userId < 0 ? -userId : userId];
                    if (simulationUser != null) (user = simulationUser).SimulationUserId = userId;
                }
            }
            if (user.IsChangeVisit) diantou.dataAccess.tcpCall.user.online(user.Id, null);
            return user;
        }
        /// <summary>
        /// 删除用户Cookie
        /// </summary>
        /// <param name="page"></param>
        private static void removeUserCookie(webPage.page page)
        {
            page.SetCookie(new fastCSharp.net.tcp.http.cookie("User", string.Empty, fastCSharp.pub.MinTime, diantou.dataModel.path.domain.Default.Domain, "/", false, false));
        }
        /// <summary>
        /// 登录处理
        /// </summary>
        /// <param name="page"></param>
        /// <param name="user"></param>
        /// <param name="isRemember">是否记住密码</param>
        internal static void Login(webPage.page page, diantou.dataAccess.user user, bool isEnterprise, bool isRemember, bool isExamDomain)
        {
            page.SetSession<webConfig.session>(new webConfig.session { Id = user.Id });
            if (isRemember && user.Password.Length != 0)
            {
                string random = fastCSharp.random.Default.SecureNextULongNotZero().toHex16();
                page.SetCookie(new fastCSharp.net.tcp.http.cookie("User", user.Id.ToString() + "." + random + "." + diantou.dataAccess.user.Md5Password(random + user.Password), date.NowSecond.AddYears(1), isExamDomain ? diantou.dataModel.path.domain.Default.ExamDomain : diantou.dataModel.path.domain.Default.Domain, "/", false, false));
                if (!isEnterprise) page.SetCookie(new fastCSharp.net.tcp.http.cookie("IndexLogin", "1", date.NowSecond.AddYears(1), diantou.dataModel.path.domain.Default.Domain, "/", false, false));
            }
        }
        /// <summary>
        /// 退出登录
        /// </summary>
        /// <param name="page"></param>
        internal static void Logout(webPage.page page)
        {
            string cookie = page.GetCookie(userCookieName);
            if (cookie != null) removeUserCookie(page);
            webConfig.session session = page.GetSession<webConfig.session>(default(webConfig.session));
            if (session.Type == webConfig.session.type.User && session.Id > 0)
            {
                page.RemoveSession();
                poll.Poll.Remove(session.Id);
            }
        }
        /// <summary>
        /// 考试登录处理
        /// </summary>
        /// <param name="page"></param>
        /// <param name="userId"></param>
        internal static void ExamLogin(webPage.page page, int userId, long mobile)
        {
            page.SetSession<webConfig.session>(new webConfig.session { Type = webConfig.session.type.ExamUser, Id = userId });
            string random = fastCSharp.random.Default.SecureNextULongNotZero().toHex16();
            page.SetCookie(new fastCSharp.net.tcp.http.cookie("ExamUser", userId.ToString() + "." + random + "." + diantou.dataAccess.user.Md5Password(random + mobile.toString()), date.NowSecond.AddDays(1), diantou.dataModel.path.domain.Default.ExamDomain, "/", false, false));
        }
        /// <summary>
        /// 获取当前考试用户
        /// </summary>
        /// <param name="page">Web页面</param>
        /// <returns>当前考试用户</returns>
        internal static diantou.examDataAccess.examUser GetExamUser(webPage.page page)
        {
            webConfig.session session = page.GetSession<webConfig.session>(default(webConfig.session));
            if (session.Type == webConfig.session.type.ExamUser) return diantou.examDataAccess.clientCache.ExamUser[session.Id];
            return getExamUser(page, true);
        }
        /// <summary>
        /// 获取当前考试用户
        /// </summary>
        /// <param name="page">Web页面</param>
        /// <returns>当前考试用户</returns>
        internal static diantou.examDataAccess.examUser GetSessionExamUser(webPage.page page)
        {
            webConfig.session session = page.GetSession<webConfig.session>(default(webConfig.session));
            if (session.Type == webConfig.session.type.ExamUser) return diantou.examDataAccess.clientCache.ExamUser[session.Id];
            return getExamUser(page, false);
        }
        /// <summary>
        /// 获取考试用户
        /// </summary>
        /// <param name="page"></param>
        /// <returns></returns>
        private static diantou.examDataAccess.examUser getExamUser(webPage.page page, bool isSetSession)
        {
            string cookie = page.GetCookie(examUserCookieName);
            if (cookie != null)
            {
                int userId;
                subArray<subString> cookies = cookie.split('.');
                if (cookies.Count == 3 && int.TryParse(cookies[0], out userId))
                {
                    diantou.examDataAccess.examUser user = diantou.examDataAccess.clientCache.ExamUser[userId];
                    if (user != null && cookies[2].Equals(diantou.dataAccess.user.Md5Password(cookies[1] + user.Mobile.toString())))
                    {
                        if (isSetSession) page.SetSession<webConfig.session>(new webConfig.session { Type = webConfig.session.type.ExamUser, Id = userId });
                        return user;
                    }
                }
            }
            return null;
        }
        ///// <summary>
        ///// 获取考试用户标识
        ///// </summary>
        ///// <param name="page">Web页面</param>
        ///// <returns>考试用户标识</returns>
        //internal static int GetExamUserId(webPage.page page)
        //{
        //    webConfig.session session = page.GetSession<webConfig.session>(default(webConfig.session));
        //    if (session.Type == webConfig.session.type.ExamUser) return session.Id;
        //    diantou.examDataAccess.examUser user = getExamUser(page);
        //    return user != null ? user.Id : 0;
        //}
        /// <summary>
        /// 获取当前考试邀请用户标识
        /// </summary>
        /// <param name="page">Web页面</param>
        /// <returns>考试邀请用户标识</returns>
        internal static int GetExamInvitationId(webPage.page page)
        {
            webConfig.session session = page.GetSession<webConfig.session>(default(webConfig.session));
            return session.Type == webConfig.session.type.ExamInvitation ? session.Id : 0;
        }
    }
}
